package com.hccl.service.classifier;

import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.nlpcn.commons.lang.tire.domain.Forest;
import org.nlpcn.commons.lang.tire.library.Library;

import java.util.List;

import static com.hccl.config.Constants.segDicPath;

/**
 * Created by sunjia on 2018/4/10.
 */
public class SegmentUtil {

    ToAnalysis analysis; //分词
    Forest forest; // 用户词典

    public SegmentUtil(){
        analysis = new ToAnalysis();
        try {
            forest= Library.makeForest(segDicPath);//加载字典文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        analysis.setForests(forest);
        analysis.parseStr("");//分词提速
    }

    //ANSJ分词，synchronized，只有一个线程能访问，其他阻塞
    public String segment(String line) throws Exception {

        String lineSeged = "";
        Result result = analysis.parse(line, forest);
        List<Term> termList = result.getTerms();
        for(Term term : termList){
            if (!term.getNatureStr().contains("w")){//过滤标点符号
                lineSeged += term.getName() + " ";
            }
        }
        lineSeged = lineSeged.trim();
        return lineSeged;
    }
}
